const express = require('express');
const router = express.Router();
const { authenticateToken } = require('../middleware/auth');
const { getCart, addToCart, updateCartItem, removeFromCart, clearCart, calculateTotal } = require('../models/cartModel');

// 获取购物车
router.get('/', authenticateToken, async (req, res) => {
    try {
        const cartItems = await getCart(req.user.id);
        res.json(cartItems);
    } catch (error) {
        res.status(500).json({ error: error.message });
    }
});

// 添加商品到购物车
router.post('/add', authenticateToken, async (req, res) => {
    try {
        const { productId, quantity = 1 } = req.body;
        await addToCart(req.user.id, productId, quantity);
        res.json({ message: '添加成功' });
    } catch (error) {
        res.status(400).json({ error: error.message });
    }
});

// 更新购物车商品数量
router.put('/:id', authenticateToken, async (req, res) => {
    try {
        const { quantity } = req.body;
        await updateCartItem(req.user.id, req.params.id, quantity);
        res.json({ message: '更新成功' });
    } catch (error) {
        res.status(400).json({ error: error.message });
    }
});

// 从购物车移除商品
router.delete('/:id', authenticateToken, async (req, res) => {
    try {
        await removeFromCart(req.user.id, req.params.id);
        res.json({ message: '删除成功' });
    } catch (error) {
        res.status(400).json({ error: error.message });
    }
});

// 清空购物车
router.delete('/', authenticateToken, async (req, res) => {
    try {
        await clearCart(req.user.id);
        res.json({ message: '清空成功' });
    } catch (error) {
        res.status(400).json({ error: error.message });
    }
});

module.exports = router; 